package com.yuecai.modules.yc_order.service.utils;

import com.yuecai.exception.SKUStockException;
import com.yuecai.modules.yc_fixed.domain.YcFixed;
import com.yuecai.modules.yc_fixed.repository.YcFixedRepository;
import com.yuecai.modules.yc_gift_good.domain.YcGift;
import com.yuecai.modules.yc_gift_good.domain.YcGiftGood;
import com.yuecai.modules.yc_gift_good.repository.YcGiftRepository;
import com.yuecai.modules.yc_gift_good.service.vo.YcGiftGoodVo;
import com.yuecai.modules.yc_goods.domain.YcGoods;
import com.yuecai.modules.yc_goods.vo.YcGoodsOrderVo;
import com.yuecai.modules.yc_goods_sku.domain.YcGoodsSku;
import com.yuecai.modules.yc_goods_sku.repository.YcGoodsSkuRepository;
import com.yuecai.modules.yc_order_goods.domain.YcOrderGoods;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

@Component
public class OrderUtils {


    @Autowired
    private YcGoodsSkuRepository ycGoodsSkuRepository;

    @Autowired
    private YcFixedRepository ycFixedRepository;

    @Autowired
    private YcGiftRepository ycGiftRepository;

    @Transactional(rollbackFor = Exception.class)
    public YcGoodsOrderVo getPriviceByLevel(Integer level, Optional<YcGoodsSku> oSku, Integer count) throws Exception {
        YcGoodsOrderVo vo = new YcGoodsOrderVo();
        if (!oSku.isPresent()){
            throw new Exception("该规格不存在！");
        }
        YcGoodsSku sku = oSku.get();
        Integer stock = sku.getStock();
        YcGoods ycGoods = sku.getYcGoods();
        if (ycGoods==null){
            throw new Exception("该商品不存在！");
        }
        Boolean status = ycGoods.getStatus();
        if (!status){
            throw new Exception("商品未上架！");
        }
        //库存逻辑
        if (count>stock){
            throw new SKUStockException(sku.getSpecValues()+"库存不足！");
        }else {
            Boolean aBoolean = sku.getIsForPurchasin();
            if (aBoolean){
                Integer integer = sku.getForPurchasing();
                //限制为0 时不做限制
                if (integer > 0){
                    if (count>integer){
                        throw new Exception(sku.getSpecValues()+"该限制最多购买"+integer+"个！");
                    }
                }
            }
        }
        BeanUtils.copyProperties(ycGoods,vo);
        vo.setCount(count);
        vo.setImage(sku.getImage());
        vo.setSkuId(sku.getId());
        vo.setSpecValues(sku.getSpecValues());
        vo.setUnitPrice(sku.getUnitPrice());
        vo.setUnit(sku.getUnit());
        BigDecimal sellPrice = sku.getSellPrice();
        //库存
        subSku(sku,count);
        //是会员 售价改成会员价格
        if (level != null && level ==2){
            BigDecimal vipDiscount = ycGoods.getVipDiscount();
            if (vipDiscount!=null){
                sellPrice = vipDiscount.divide(new BigDecimal(100)).multiply(sellPrice);
            }
        }
        vo.setSellPrice(sellPrice);
        return vo;
    }

    public YcOrderGoods getOrderGood(YcGoodsOrderVo goods, String s, Integer count) {

        YcOrderGoods orderGoods = new YcOrderGoods();
        BeanUtils.copyProperties(goods,orderGoods);
        orderGoods.setId(null);
        orderGoods.setGoodsName(goods.getName());
        orderGoods.setGoodsId(goods.getId());
        orderGoods.setOrderSn(s);
        orderGoods.setSellPrice(goods.getSellPrice());
        orderGoods.setSpecValues(goods.getSpecValues());
        orderGoods.setSkuId(goods.getSkuId());


        return orderGoods;
    }

    //TODO 改完此处加锁
    @Transactional(rollbackFor = Exception.class)
    void subSku(YcGoodsSku sku,Integer count){
        Integer stock = sku.getStock();
        Integer sales = sku.getSales();
        //加销量
        sales = sales + count;
        //减库存
        int i = stock - count;
        sku.setStock(i);
        sku.setSales(sales);
        ycGoodsSkuRepository.save(sku);
    }




    /**
     * 比较总价
     * @param total
     */
    public ResponseEntity checkTotalPrice(BigDecimal total) throws Exception {
        Optional<YcFixed> freight_lower_limit = ycFixedRepository.findByValue("FREIGHT_LOWER_LIMIT");
        if (freight_lower_limit.isPresent()){
            YcFixed ycFixed = freight_lower_limit.get();
            String content = ycFixed.getContent();
            BigDecimal bigDecimal = new BigDecimal(content);
            int i = bigDecimal.compareTo(total);
            if (bigDecimal.compareTo(total)==1){
                return ResponseEntity.status(400).body("消费需满足"+content+" 元");
            }
        }
        return null;
    }

    public static void main(String[] args) {
        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("1",2);
        objectObjectHashMap.putAll(null);
    }
    /**
     * 计算赠品
     * @param total
     */
    public HashMap<String,Object> giftGoodVo(BigDecimal total) {
        try {
            YcGift ycGift = ycGiftRepository.findByLowerLimitLessThanEqualAndUpperLimitGreaterThan(total, total);
            if (ycGift!=null){
                List<YcGiftGood> ycGiftGoodList = ycGift.getYcGiftGoodList();
                ArrayList<YcGiftGoodVo> vos = new ArrayList<>();
                for (YcGiftGood ycGiftGood : ycGiftGoodList) {
                    YcGiftGoodVo ycGiftGoodVo = new YcGiftGoodVo();
                    BeanUtils.copyProperties(ycGiftGood,ycGiftGoodVo);
                    Optional<YcGoodsSku> byId = ycGoodsSkuRepository.findById(ycGiftGood.getSkuId());
                    if (byId.isPresent()){
                        YcGoodsSku ycGoodsSku = byId.get();
                        ycGiftGoodVo.setYcGoodsSku(ycGoodsSku);
                        vos.add(ycGiftGoodVo);
                    }
                }
                if (CollectionUtils.isNotEmpty(vos)){
                    BigDecimal upperLimit = ycGift.getUpperLimit();
                    BigDecimal lowerLimit = ycGift.getLowerLimit();
                    HashMap<String, Object> objectObjectHashMap = new HashMap<>();
                    objectObjectHashMap.put("giftGoods",vos);
                    objectObjectHashMap.put("giftLowerLimit",lowerLimit);
                    objectObjectHashMap.put("giftUpperLimit",upperLimit);
                    return objectObjectHashMap;
                }
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 计算赠品
     * @param total
     */
    public List<YcGiftGoodVo> giftGood(BigDecimal total) {
        try {
            YcGift ycGift = ycGiftRepository.findByLowerLimitLessThanEqualAndUpperLimitGreaterThan(total, total);
            if (ycGift!=null){
                List<YcGiftGood> ycGiftGoodList = ycGift.getYcGiftGoodList();
                ArrayList<YcGiftGoodVo> vos = new ArrayList<>();
                for (YcGiftGood ycGiftGood : ycGiftGoodList) {
                    YcGiftGoodVo ycGiftGoodVo = new YcGiftGoodVo();
                    BeanUtils.copyProperties(ycGiftGood,ycGiftGoodVo);
                    Optional<YcGoodsSku> byId = ycGoodsSkuRepository.findById(ycGiftGood.getSkuId());
                    if (byId.isPresent()){
                        YcGoodsSku ycGoodsSku = byId.get();
                        ycGiftGoodVo.setYcGoodsSku(ycGoodsSku);
                        vos.add(ycGiftGoodVo);
                    }
                }
                return vos;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 赠品
     * @param payPrice
     * @param specialOffer
     * @param orderGoods
     * @param s
     * @return
     */
    public List<YcOrderGoods> submitOrderGiftGood(BigDecimal payPrice, BigDecimal specialOffer, List<YcOrderGoods> orderGoods,String s) {
        try {
            payPrice = payPrice.subtract(specialOffer);
            List<YcGiftGoodVo> ycGoodsSkus = giftGood(payPrice);
            if (CollectionUtils.isEmpty(ycGoodsSkus)){
                return orderGoods;
            }
            for (YcGiftGoodVo item : ycGoodsSkus) {
                YcGoodsSku goodsSkus = item.getYcGoodsSku();
                YcGoods goods = goodsSkus.getYcGoods();

                YcOrderGoods orderGood = new YcOrderGoods();
                BeanUtils.copyProperties(goods,orderGood);
                orderGood.setId(null);
                orderGood.setGoodsName(goods.getName());
                orderGood.setGoodsId(goods.getId());
                orderGood.setOrderSn(s);
                orderGood.setSellPrice(BigDecimal.valueOf(0));
                orderGood.setSpecValues(goodsSkus.getSpecValues());
                orderGood.setSkuId(goodsSkus.getId());
                orderGood.setImg(goods.getImg());
                orderGood.setUnit(goodsSkus.getUnit());
                orderGood.setCount(item.getCount());
                orderGood.setGainType(2);
                orderGood.setUnitPrice(goodsSkus.getUnitPrice());
                orderGoods.add(orderGood);
                return orderGoods;
            }
        }catch (Exception e){
            e.printStackTrace();
        }


        return orderGoods;
    }
}
